angular.module('publish.cibtent.controllers', [])
	//发布内容
	.controller('publish-contentCtrl', function($ionicModal,$window,$ionicPopup, $http,$ionicLoading, $scope, $stateParams, $state, $ionicViewSwitcher, $ionicActionSheet, $timeout) {
		//	console.log($stateParams.huodongId);
		$scope.title = $stateParams.contentId;
		$scope.mapnr = mapcont;//获取地址
		$scope.ksdate;
	
		$scope.Atheme={theme:'',ksdate:'',jsdate:'',bmjzdate:'',jbdd:''};//活动主题
			$scope.back=function(){
			$ionicViewSwitcher.nextDirection('back');
			
			location.href='#/tab/Selected';

		}
		$scope.showAlert = function(str) {
						     var alertPopup = $ionicPopup.alert({
						       title: '提示框',
						       template: str
						     });
						     alertPopup.then(function(res) {
						       console.log('Thank you for not eating my delicious ice cream cone');
						     });
						   };//提示框
		$scope.$on('$ionicView.beforeEnter', function() {
			$scope.mapnr = mapcont;
		});
		//获取主题
		$scope.notices=[];
		$http.get(ServerAddress + "api/theme/get").success(function(data) {
					for(var i=0;i<data.length;i++)
            {
            
                $scope.notices.push({Id:data[i].Id,name:data[i].名称});
            }	
						 
						console.log(data[0].Id);
				});
		$scope.fmpd = false;
		$scope.FormData = null;
		var hdfm = document.getElementById('hdfm');
		hdfm.addEventListener('change', readFile, false);
		function readFile() {
			var file = this.files[0];
			var value = $("#hdfm").val();

			var yy = true;
			//	$ionicLoading.show();
			if(value == null || value == "") {

			} else {

				//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件 
				if(!/image\/\w+/.test(file.type)) {
					alert("请确保文件为图像类型");
					return false;
				}
				var reader = new FileReader();
				reader.readAsDataURL(file);
				//console.log(this.result); 

				reader.onload = function(e) {
					//console.log(this.result);
					if(yy) {
						$scope.FormData = this.result;
						//	$ionicLoading.hide();
						$scope.fmpd = true;
					}
					y = false;
				}
			}
		}
		$scope.change = function() {
			
			
			var formData = new FormData($("#uploadForm")[0]);
			var hdfm = document.getElementById('hdfm');
			if(localStorage.getItem('userphone') != null) {
				$.ajax({
					url: ServerAddress + 'api/' + localStorage.getItem('userphone') + '/image/upload',
					type: 'POST',
					data: formData,
					cache: false,
					contentType: false,
					processData: false,
					success: function(data) {
						console.log(data);
						$timeout(function() {
							//		$ionicLoading.hide();
							
							$scope.FormData = data;
							$scope.fmpd = true;
						}, 3000);
					},
					error: function(returndata) {
						console.log(returndata);
					}
				})
			}
			// $ionicLoading.show();

		}
		$scope.csfm = function() {

			var hdfm = document.getElementById('hdfm');
			if($scope.FormData != null) {
				$scope.show();
			} else
				hdfm.click();
		}
		$scope.show = function() {
			// 显示上拉菜单
			var hideSheet = $ionicActionSheet.show({
				buttons: [{
					text: '修改'
				}],
				destructiveText: '删除',
				titleText: '活动封面',
				cancelText: '取消',
				cancel: function() {
					// 这里添加取消代码
				},
				destructiveButtonClicked: function() {
					$scope.fmpd = false
					$scope.FormData = null;
					return true;
				},
				buttonClicked: function(index) {
					hdfm.click();
					return true;
				}
			});

		};
		$scope.$on($scope.fabu);
		$scope.addimg = function() {

			var hdnrtp = document.getElementById('hdnrtp');
			hdnrtp.click();
			var text = document.getElementById('text');
			text.innerHTML = text.innerHTML;

		}
		$scope.del = function() {
			document.getElementById('text').innerHTML = '';
		}
		$scope.fabu = function() {
			console.log(localStorage.getItem('userphone'));
				
				var aa=new Date(document.getElementById('ksdate').value);
				;
			//	var b=new Date(1459382400000).Format("yyyy-MM-ddThh:mm:ss"); 
				
				//
				console.log(aa);
			console.log(aa=='Invalid Date' );
		//	console.log(new Date(b).getFullYear());
			if(localStorage.getItem('userphone') != null) {
				if($scope.FormData!=null)
				{
					if($scope.Atheme.theme!=null && $scope.Atheme.theme!="")
					{
						$scope.Atheme.ksdate=new Date(g('ksdate').value);
						if($scope.Atheme.ksdate!='Invalid Date')
						{
							console.log($scope.Atheme.ksdate);
							$scope.Atheme.jsdate=new Date(g('jsdate').value);
					
							if($scope.Atheme.jsdate!='Invalid Date')
							{	
								console.log($scope.Atheme.jsdate);
								$scope.Atheme.jbdd=g('jbdd').value;
								
								if($scope.Atheme.jbdd!="")
								{
									console.log($scope.Atheme.jbdd)
									$scope.Atheme.bmjzdate=new Date(g('bmjzdate').value);
									if($scope.Atheme.bmjzdate!='Invalid Date')
									{
										var text = document.getElementById('text');
										
										if(text.innerHTML!=null && text.innerHTML!='' && text.innerHTML!='undefined')
										{
											console.log(g('zhuti').value);
											//时间验证
											var dqy=new Date().getFullYear()
											if($scope.Atheme.ksdate.getFullYear()>=dqy)
											{
													if($scope.Atheme.jsdate>$scope.Atheme.ksdate)
													{
														if($scope.Atheme.bmjzdate<=$scope.Atheme.jsdate &&$scope.Atheme.bmjzdate.getFullYear()>=dqy )
															{
																var json = JSON.stringify({
																标题: $scope.Atheme.theme,
																内容: text.innerHTML,
																主题图片: $scope.FormData,
																活动地址: $scope.Atheme.jbdd,
																开始时间: $scope.Atheme.ksdate,
																结束时间: $scope.Atheme.jsdate,
																报名截止时间:$scope.Atheme.bmjzdate,
																主题Id:g('zhuti').value
															});
															$ionicLoading.show({
																template:'正在发布..',
																noBackdrop:false
															});
															console.log(json);
															$http.post(ServerAddress + "api/activity/"+localStorage.getItem('userphone')+"/add", json).success(function(response) {
																if(response==1)
																{
																	$ionicLoading.show({
																template:'发布成功..',
																noBackdrop:true,
																duration:500
																});
																$scope.Atheme.theme="";
																text.innerHTML="";
																$scope.FormData=null;
																$scope.fmpd=false;
																g('ksdate').value=null;
																g('jsdate').value=null;
																g('bmjzdate').value=null;
																g('jbdd').value=null;
																$timeout(function() {
																	location.href='#/tab/Selected';							
																}, 1);
																}
																
															//	$ionicLoading.hide();
															//alert('注册成功！');
																
															//location.href = '#/tab/Selected';	
															});
															}
															else
															{
																$scope.showAlert('报名截止时间要在结束时间之前！');
															}
													}
													else
													{
														$scope.showAlert('结束时间要在开始时间之后');
													}
											}
											else
											{
												$scope.showAlert('开始时间不正确');
											}
												
												
										}
										else
										{
											$scope.showAlert('活动内容为空！');
										}
									}
									else
									{
										$scope.showAlert('截止日期为空或无效！');
									}
								}
								else
								{
									$scope.showAlert('举办地点不能为空');
								}
								
							}
							else{
									$scope.showAlert('结束日期为空或无效！');
							}
						}
						else
						{
							$scope.showAlert('开始日期为空或无效！');
						}
					}
					else
					{
						$scope.showAlert('缺少主题！');
					}
				}
				else
				{
						
						   $scope.showAlert('缺少活动封面!');
				}
			} else {
				//  confirm 对话框
				$scope.showConfirm = function() {
					var confirmPopup = $ionicPopup.confirm({
						title: '提示框',
						template: '请先登入!',
						okText: '是',
						cancelText: '否'
					});
					confirmPopup.then(function(res) {
						if(res) {
							localStorage.setItem('longipd', 1);
							console.log(localStorage.getItem('userphone'));
							console.log(localStorage.getItem('longipd'));
							$ionicViewSwitcher.nextDirection('forward')
								//			//	$state.go('tab.login');
							location.href = '#/login';
						} else {
							console.log('You are not sure');
						}
					});
				};

				$scope.showConfirm();
			}
		};
		//		$(document).ready(function(){
		//	$(document.body).height($(window).height());
		//	alert($(window).height());
		//});
		var hdnrtp = document.getElementById('hdnrtp');
		hdnrtp.addEventListener('change', readFile1, false);

		function readFile1() {
			var file1 = this.files[0];
			var value2 = $("#hdnrtp").val();

			// $ionicLoading.show();
			if(value2 == null || value2 == "") {

				text.innerHTML = '111';
			} else {

				//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件 
				if(!/image\/\w+/.test(file1.type)) {
					alert("请确保文件为图像类型");
					return false;
				}
				var reader = new FileReader();
				reader.readAsDataURL(file1);
				//console.log(this.result); 

				reader.onload = function(e) {
					var formData = new FormData($("#uploadForm1")[0]);
					var aaa = this.result;
					if(localStorage.getItem('userphone') != null) {
						$.ajax({
							url: ServerAddress + 'api/' + localStorage.getItem('userphone') + '/image/upload',
							type: 'POST',
							data: formData,
							cache: false,
							contentType: false,
							processData: false,
							success: function(data) {
								console.log(data);
								text.innerHTML = text.innerHTML + '<img id="' + data.substr(33, data.length) + '" src=' + aaa + ' style="max-width:100%;max-height:15rem;" />' + "<br />" + "<br />";
								$timeout(function() {
									//		$ionicLoading.hide();
									document.getElementById(data.substr(33, data.length)).src = data;
								}, 3000);
							},
							error: function(returndata) {
								console.log(returndata);
							}
						})
					} else {
						text.innerHTML = text.innerHTML + '<img  src=' + aaa + ' style="max-width:100%;max-height:15rem;" />' + "<br />" + "<br />";
					}
					//console.log(this.result);
//$ionicHistory.clearCache([$state.current.name])
				}
			}
		}

	})

	//发布内容map
	.controller('mapCtrl', function($scope, $ionicHistory, $window, $ionicViewSwitcher) {
$scope.back=function(){
			console.log(10);
$ionicViewSwitcher.nextDirection('back');
			$window.history.back();

		}
	$scope.mapwc = function() {

		$ionicViewSwitcher.nextDirection('back')
		$ionicHistory.goBack();

	}
	window.addEventListener('message', function(event) {
		// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
		var loc = event.data;
		console.log('location', loc);

		if(loc && loc.module == 'locationPicker') { //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
			console.log('location', loc);
			console.log(loc.poiaddress);
			mapcont = loc.poiaddress + "(" + loc.poiname + ")";
			console.log(loc.cityname);

		}

	}, false);

	//mapcont

})
	function g(x)
	{
	return	document.getElementById(x)
	}
	Date.prototype.Format = function(fmt)   {

	var o = {       "M+" : this.getMonth()+1,                 //月份
	"d+" : this.getDate(),                    //日    
	"h+" : this.getHours(),                   //小时    
	"m+" : this.getMinutes(),                 //分   
	"s+" : this.getSeconds(),                 //秒    
	"q+" : Math.floor((this.getMonth()+3)/3), //季度   
	"S"  : this.getMilliseconds()             //毫秒 
	};     
	if(/(y+)/.test(fmt))
	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));     for(var k in o)       if(new RegExp("("+ k +")").test(fmt))     
	fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));     return fmt;   };